package com.neusoft.neuhealth.interceptor;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.neuhealth.po.Result;
import com.neusoft.neuhealth.po.user.JWTUtil;
import com.neusoft.neuhealth.service.RedisService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;


import java.util.Map;
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    private RedisService redisService;
    public JWTInterceptor(RedisService redisService) {
        this.redisService = redisService;
    }
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取请求头
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
        }
        //准备一个用于给前端返回结果的map
        Result rm=new Result();
        try {
        //如果携带token,则验证token
        if (token != null) {
            // 验证token
            //JWTUtil.verify(token);
            DecodedJWT verify = JWTUtil.verify(token);
            Map<String, Claim> map= JWTUtil.getPayloadFromToken(token);
            String userName=map.get("userName").asString();
            String password=map.get("password").asString();
           // 从redis中获取token
            String redisToken = redisService.getToken(userName);
            if (redisToken != null && redisToken.equals(token)) {
                // 验证通过
                return true;
            }else{
                rm.setCode(401);
                rm.setMessage("token验证失败");
            }

        }else{
            rm.setCode(401);
            rm.setMessage("token为空,您的登录状态已过期，请重新登录");
        }
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            rm.setCode(401);
            rm.setMessage("签名不一致，请重新登录");
            log.info("签名不一致，请重新登录");

        } catch (Exception e) {
            e.printStackTrace();

            rm.setCode(401);
            rm.setMessage("token无效，请重新登录");
            log.info("token无效，请重新登录");
        }
        //响应到前台: 将map转为json
        String json = new ObjectMapper().writeValueAsString(rm);//{key:value}
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;

    }

}
